<?php


if (!extension_loaded("pdo")) die("Missing PDO PHP extension."); // check if extension loaded
class DB {
	private static $conn = NULL;
	public static $err = NULL;
    public static $dbname;
	public static $hostname;
	public static $dbusername;
	public static $dbpassword;
	public static $numofrows=0;
	public static $affectedrows=0;
    public static $portnumber=3306;
    public static $dbtype="mysql";
	/**
	 * Connects to SQL Server
	 * 
	 * @return	true/false
	 */
     
   public static function connect()
	{
		// set OPTIONS
	    $options = array(
	        PDO::ATTR_PERSISTENT => true,
	        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
	    );
	    
        try {
			switch (strtolower(self::$dbtype)) {
				case "mysql":
					if (!extension_loaded("pdo_mysql")) die("Missing pdo_mysql PHP extension."); // check if extension loaded
					if(empty(self::$portnumber)) self::$portnumber=3306;
					self::$conn = new PDO("mysql:host=".self::$hostname.";port=".self::$portnumber.";dbname=".self::$dbname, self::$dbusername, self::$dbpassword);
					break;
				
				case "pgsql":
					if (!extension_loaded("pdo_pgsql")) die("Missing pdo_pgsql PHP extension."); // check if extension loaded
					if(empty(self::$portnumber)) self::$portnumber=5432;
					self::$conn = new PDO("pgsql:host=".self::$hostname.";port=".self::$portnumber.";dbname=".self::$dbname, self::$dbusername, self::$dbpassword);
					break;
					
				case "sqlite":
					if (!extension_loaded("pdo_sqlite")) die("Missing pdo_sqlite PHP extension."); // check if extension loaded	
					$rootdir = dirname(__FILE__)."/../../";
					$dbfile  = $rootdir."database/".self::$dbname.".db";
					$created = false;
					if(!file_exists($rootdir."database/")) {
						// try to create the database folder
						@mkdir($rootdir."database", 0777, true);			
					}
					if(!file_exists($dbfile)) {
						// try to create the database file
						if(@touch($dbfile))
							$created = true;
					}
					if(!file_exists($rootdir."database/.htaccess")) {
						// try to create the htaccess file
						@file_put_contents($rootdir."database/.htaccess", "Deny from all");
					}
					if(file_exists($dbfile) && is_readable($dbfile) && is_writable($dbfile)) {
						self::$conn = new PDO("sqlite:".$dbfile, self::$dbusername, self::$dbpassword);
						//if($created)
							//self::$conn->exec(file_get_contents($rootdir."sql/".$conf["server"]."/sqlite.sql"));
					} else {
						self::$err = "cant crate the sqlite database";
						return false;
					}
					break;
					
				default:
					self::$err = "not supported database type";
					return false;
					break;
			}
			return true;
		} catch (PDOException $e) {
			self::$err = $e->getMessage();
			return false;
		}
		
	}
    
	
	
	/*
	 * close the database connection
	 */
	public static function close () {
		self::$conn = NULL;
	}
	
	/**
	 * Sends a database query to SQL server.
	 *
	 * @param	string		$res 		a database query
	 * @param	array		$bind 		
	 * @return 	integer					id of the query result
	 */
	public static function query ($res, $bind = array()) {
		try {
			$query = Null;
			$query = self::$conn->prepare($res);
            
			if(is_array($bind) && !empty($bind))
				$query->execute($bind);
			else
				$query->execute();
            self::$affectedrows=$query->rowCount();     
			return $query;
		} catch (PDOException $e) {
			self::$err = $e->getMessage();
		}
	}

	
	/**
	 * Gets a row from SQL database query result.
	 *
	 * @param	string		$res		a database query
	 * @return 				array		a row from result
	 */
	public static function fetch_array ($res) {
		try {
            # Affected Rows?
			// 1
			$row = $res->fetchAll();
			
			for($i=0;$i<count($row);$i++)
			{
				foreach($row[$i] as $key=>$value)
				{
					$row[$i][$key]=trim(stripcslashes($value));
				}
			}
			return $row;
            
			//return $res->fetch(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			self::$err = $e->getMessage();
		}
	}
    
    public static function fetch_num_of_rows ($res) {
		try {
            # Affected Rows?
			self::$affectedrows=$res->rowCount(); // 1
			$row = $res->fetchAll();
			
			for($i=0;$i<count($row);$i++)
			{
				foreach($row[$i] as $key=>$value)
				{
					$row[$i][$key]=trim(stripcslashes($value));
				}
			}
			return count($row);
            
			//return $res->fetch(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			self::$err = $e->getMessage();
		}
	}
	
	/**
	 * return the last insert id
	 */
	public static function last_id () {
		return self::$conn->lastInsertId();
	}
	
	/**
	 * Returns SQL error number for last error.
	 *
	 * @return 	integer		MySQL error number
	 */
	public static function error () {
		return self::$err;
	}
    
    public static function updatecheckExistance($tablename,$conditionarr=array(),$idconditionarray=array())
    {
        $selectquery=self::createSelectquerybasedonparams($tablename,$conditionarr);
        $bindarray=self::getBindarray($conditionarr);
        if(count($idconditionarray)>0)
        {
            $selectquery.=" and id != :id";
            $bindarray[":id"]=$idconditionarray['id'];
        }
        $fetchinfo=self::fetch_array(self::query($selectquery,$bindarray));
        if(count($fetchinfo)>0)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    
    public static function checkExistance($tablename,$conditionarr=array())
    {
        $selectquery=self::createSelectquerybasedonparams($tablename,$conditionarr);
        $bindarray=self::getBindarray($conditionarr);
        $fetchinfo=self::fetch_array(self::query($selectquery,$bindarray));
        if(count($fetchinfo)>0)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    
    public static function insertData($tablename,$fieldarray=array())
    {
        $insertquery=self::createInsertquerybasedonparams($tablename,$fieldarray);
        $bindarray=self::getBindarray($fieldarray);
        self::query($insertquery,$bindarray);
    }
    
    public static function updateData($tablename,$fieldarray=array(),$conditionarray=array())
    {
        $updatequery=self::createUpdatequerybasedonparams($tablename,$fieldarray,$conditionarray);
        $resultarray = array_merge($fieldarray, $conditionarray);
        $bindarray=self::getBindarray($resultarray);
        self::query($updatequery,$bindarray);
    }
    
    
    public static function deleteData($tablename,$conditionarray=array())
    {
        $deletequery=self::createDeletebasedonparams($tablename,$conditionarray);
        $bindarray=self::getBindarray($conditionarray);
        self::query($deletequery,$bindarray);
    }
    public static function createSelectquerybasedonparams($tables="users",$fieldarray=array())
    {
        $sqlquery="select id from ".$tables;
        if(count($fieldarray)>0)
        {
            $sqlquery.=" where ";
            foreach($fieldarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key." and ";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-4);
        }
        return $sqlquery;
    }
    
    public static function createInsertquerybasedonparams($tables="users",$fieldarray=array())
    {
        $sqlquery="insert into ".$tables." set ";
        if(count($fieldarray)>0)
        {
            foreach($fieldarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key.",";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-1);
        }
        return $sqlquery;
    }
    
    public static function getBindarray($fieldarray=array())
    {
        $bindarray=array();
        foreach($fieldarray as $key=>$value)
    	{
    		$bindarray[":".$key]=$value;
    	}
        return $bindarray;
    }
    
    public static function createUpdatequerybasedonparams($tables="users",$fieldarray=array(),$conditionarray=array())
    {
        $sqlquery="update ".$tables." set ";
        if(count($fieldarray)>0)
        {
            foreach($fieldarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key.",";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-1);
        }
        if(count($conditionarray)>0)
        {
            $sqlquery.=" where ";
            foreach($conditionarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key." and ";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-4);
        }
        
        return $sqlquery;
    }
    
    public static function createDeletebasedonparams($tables="users",$conditionarray=array())
    {
        $sqlquery="delete from ".$tables." ";
        if(count($conditionarray)>0)
        {
            $sqlquery.=" where ";
            foreach($conditionarray as $key=>$value)
    		{
    			$sqlquery.=$key."=:".$key." and ";
    		}
            $sqlquery=substr($sqlquery,0,strlen($sqlquery)-4);
        }
        
        return $sqlquery;
    }
    
}
?>
